package com.black.service.config;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.Properties;

@Slf4j
@Setter
@Configuration
@ConfigurationProperties(prefix = "spring.datasource")
@MapperScan(basePackages = "com.black.service.dao", sqlSessionFactoryRef = "blackSqlSessionFactory")
public class DataSourceConfig {
    private String driverClassName;
    private String url;
    private String username;
    private String password;
    //采用druid密码回调,获取连接时解密
    private String callback;

    @Bean(name = "blackDataSource")
    @Primary
    public DataSource blackDataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(driverClassName);
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        Properties properties = new Properties();
        properties.setProperty("config.decrypt", "true");
        properties.setProperty("password", password);
        druidDataSource.setConnectProperties(properties);
        try {
            druidDataSource.setPasswordCallbackClassName(callback);
        } catch (Exception e) {
            log.error("druid passwordCallbackClassName error", e);
        }
        return druidDataSource;
    }

    @Bean(name = "blackTransactionManager")
    @Primary
    public DataSourceTransactionManager blackTransactionManager() {
        return new DataSourceTransactionManager(blackDataSource());
    }

    @Bean(name = "blackSqlSessionFactory")
    @Primary
    public SqlSessionFactory blackSqlSessionFactory(@Qualifier("blackDataSource") DataSource dataSource) throws Exception {
        final SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean.getObject();
    }

}
